import React, { useState, useEffect } from 'react';
import { DbValue } from '../ctl/value';
import { get_num, obj_str, is_empty, IkSelect, CkValue, useCheck, Dlg, useForm, obj_empty, ck_empty, IkInput, loc } from 'sui';
import { get_plc, s7_type } from '../cmd/base';
import { load_id } from '../cmd/load';

const find_id = (main) => {
    const set = new Set();
    if (!is_empty(main)) {
        main.forEach(d => set.add(obj_str(d, "uid")));
    }

    for (let i = 1; i <= 100; i++) {
        const id = `plc${i}`;
        if (set.has(id)) {
            continue;
        }

        return id;
    }

    return null;
};

const PlcAdd = ({ umd, open, setOpen, hcmd, main }) => {
    const [open_db, openDb] = useState(false);
    const [value, setValue] = useState();
    const [fin, setFin] = useState();
    const form = useForm(setValue);
    const [open_check, openCheck, hcheck] = useCheck();

    useEffect(() => {
        if (!open) {
            return;
        }

        const cur = umd.cur;

        if (obj_empty(cur)) {
            setValue({
                rank: "0",
                slot: "0",
            });

        }
        else {
            load_id(obj_str(cur, "id"), v => {
                setValue(v);
            });
        }
    }, [open, umd.cur]);

    useEffect(() => {
        if (!open) {
            return;
        }

        const type = obj_str(value, "type");
        setFin(type);

    }, [open, value]);

    const ckdes = {
        name: loc("ms"),
        ip: loc("ip"),
        trigger: loc("mg_285"),
    };

    const hdone = () => {
        const cur = umd.cur;

        const ck = {
            name: (v) => {
                const e = ck_empty(v, loc("ms"));
                if (e) {
                    return e;
                }

                if (is_empty(main)) {
                    return null;
                }

                const f = main.find(d => {
                    if (umd.fin !== "copy" && cur) {
                        if (cur.uid === d.uid) {
                            return false;
                        }
                    }

                    return v === d.value;
                });

                if (f) {
                    return loc("mg_277");
                }

                return null;
            },
            ip: (v) => ck_empty(v, loc("ip")),
            type: (v) => ck_empty(v, loc("cmd_27")),
            tp: (v) => {
                if (fin !== "s7") {
                    return null;
                }

                return ck_empty(v, loc("mg_293"));
            },
            rank: (v) => {
                if (fin !== "s7") {
                    return null;
                }

                const t = parseInt(v, 10);
                if (isNaN(t)) {
                    return loc("zh_2");
                }

                return null;
            },
            slot: (v) => {
                if (fin !== "s7") {
                    return null;
                }

                const t = parseInt(v, 10);
                if (isNaN(t)) {
                    return loc("zh_2");
                }

                return null;
            },
        };

        if (!form.hcheck(ck, value)) {
            return;
        }

        const cmd = {
            ip: obj_str(value, "ip"),
            name: obj_str(value, "name"),
            type: obj_str(value, "type"),
        };

        if (fin === "s7") {
            cmd["rank"] = get_num(value, "rank");
            cmd["slot"] = get_num(value, "slot");
            cmd["tp"] = obj_str(value, "tp");
        }

        let url = null;
        let id = null;

        if (obj_empty(cur)) {
            id = find_id(main);
            url = "add";
        }
        else {
            if (umd.fin === "copy") {
                id = find_id(main);
                url = "copy";
            }
            else {
                id = obj_str(cur, "id");
                url = "update";
            }
        }

        if (!id) {
            alert(loc("cmd_24"));
            return;
        }

        cmd["id"] = id;
        cmd["uid"] = id;

        form.hclear();
        setOpen(false);
        hcmd(cmd, url, obj_str(cur, "uid"));
    };

    const getView = () => {
        if (fin === "s7") {
            return (
                <>
                    <IkInput label={loc("zh_8")} name="rank" form={form} value={value}/>
                    <IkInput label={loc("zh_9")} name="slot" form={form} value={value}/>
                    <IkSelect label={loc("mg_293")} name="tp" form={form} value={value} lst={s7_type()}/>
                </>
            );
        }

        return null;
    };

    const hcancel = () => {
        form.hclear();
        setOpen(false);
    };

    const hdb = (val) => {
        setValue({
            ...value,
            trigger: val,
        });
    };

    return (
        <Dlg open={open} hcmd={() => hcheck(value, ckdes, hdone)} title={loc("cmd_25")} hcancel={hcancel}>
            <div className="flex flex-col">
                <IkInput label={ckdes.name} name="name" form={form} value={value}/>
                <IkInput label={ckdes.ip} name="ip" form={form} value={value}/>
                <IkSelect label={loc("lx")} name="type" form={form} value={value} lst={get_plc()} disabled={umd.fin === "copy"}/>
                {getView()}
            </div>
            <CkValue setOpen={openCheck} open={open_check} value={value} des={ckdes} setValue={setValue} hcmd={hdone}/>
            <DbValue open={open_db} setOpen={openDb} cur={obj_str(value, "trigger")} hcmd={hdb}/>
        </Dlg>
    );
};

export {PlcAdd};
